//
//  PEWebService.m
//  ChronicDiseaseManager
//
//  Created by CDCT on 2017/10/17.
//  Copyright © 2017年 cdct. All rights reserved.
//
#import "SKWebService.h"
#import "ZCBaseUserManager.h"

@interface SKWebService()

/** key is urlString, value is AFHTTPSessionManager */
@property (nonatomic, strong) NSMutableDictionary *sessionManagerMDic;

@property (nonatomic, strong) NSString *userAgentStr;
@property (nonatomic, strong) NSString *deviceIDStr;


@end


@implementation SKWebService

- (instancetype)initWebServiceWithUserAgent:(NSString *)userAgentStr
                                     deviceID:(NSString *)deviceIDStr
{
    if (self = [super init]) {
//        SKWebService *webService = [[SKWebService alloc] init];
        self.userAgentStr = userAgentStr;
        self.deviceIDStr  = deviceIDStr;
    }
    return self;
}

static AFHTTPSessionManager *SessionManager ;
- (AFHTTPSessionManager *)sharedHTTPSession {
    if (!SessionManager) {
        extern NSString *baseURLStr;
//        SessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURLStr]];
        SessionManager = [AFHTTPSessionManager manager];
        SessionManager.requestSerializer.timeoutInterval = 30;
        //        SessionManager.responseSerializer= [AFHTTPResponseSerializer serializer];
        SessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                          @"text/plain", @"text/json", @"text/javascript",
                          @"text/html", nil];
        SessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [SessionManager.requestSerializer setValue:@"0"
                              forHTTPHeaderField:@"platform"];
        [SessionManager.requestSerializer setValue:@"wzg"
                                forHTTPHeaderField:@"merchant"];
        [SessionManager.requestSerializer setValue:@"2"
                                forHTTPHeaderField:@"Live-Platform"];
        [SessionManager.requestSerializer setValue:@"iPhone" forHTTPHeaderField:@"User-Agent"];
        
        [SessionManager.requestSerializer setValue:self.deviceIDStr forHTTPHeaderField:@"device_id"];
        
        // MARK: - SSL
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//        SessionManager.securityPolicy = securityPolicy;
//        // 2.设置证书模式
//        NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"api.mall.ryg0212.com" ofType:@"cer"];
//        NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
//        SessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate
//                                                         withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];
//        // 客户端是否信任非法证书
//        SessionManager.securityPolicy.allowInvalidCertificates = YES;
//        // 是否在证书域字段中验证域名
//        [SessionManager.securityPolicy setValidatesDomainName:NO];
    }
  NSString *accessToken = [ZCBaseUserManager shareInstance].userModel.member.accessToken;
  if (accessToken != nil) {
      [SessionManager.requestSerializer setValue:[@"Bearer " stringByAppendingString:accessToken]
                            forHTTPHeaderField:@"Authorization"];

      [SessionManager.requestSerializer setValue:[@"Bearer " stringByAppendingString:accessToken]
                            forHTTPHeaderField:@"auth-key"]; //消息IM未读消息需要【暂时留空】
  } else {
    [SessionManager.requestSerializer setValue:@"Bearer "
                            forHTTPHeaderField:@"Authorization"];
  }
    //直播live
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    ZCBaseUserModel *userModel = manager.userModel;
    NSString *liveToken = userModel.member.liveToken;
    if (liveToken != nil) {
        [SessionManager.requestSerializer setValue:liveToken
                              forHTTPHeaderField:@"liveToken"];
    }
    
    return SessionManager;
}

- (AFHTTPSessionManager *)createSessionManagerWithUrl:(NSString *)urlString
{
    if (nil == urlString) {
        extern NSString *baseURLStr;
        urlString = baseURLStr;
    }
  
    AFHTTPSessionManager *sharedClient = [self sharedHTTPSession];
    
    return sharedClient;
    
}

// MARK: -  Public Methods

- (void)updateRequestSerializerHeadFieldWithDic:(NSDictionary *)dic baseURL:(NSString *)baseUrlStr
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    for (NSString *key in [dic allKeys]) {
        [manager.requestSerializer setValue:[dic objectForKey:key]
                         forHTTPHeaderField:key];
    }
}

// MARK: -  POST

- (NSURLSessionDataTask *)postWithBaseUrl:(NSString *)baseUrlStr
                                     path:(NSString *)path
                               parameters:(id)parameters
                                 progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                                  success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                  failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    if (nil == parameters) {
        parameters = [[NSDictionary alloc] init];
    }
    
    NSURLSessionDataTask *task = [manager POST:baseUrlStr
                                    parameters:parameters
                                      progress:uploadProgress
                                       success:success
                                       failure:failure];
    
    return task;
}


// MARK: -  GET

- (NSURLSessionDataTask *)getWithBaseUrl:(NSString *)baseUrlStr
                                    path:(NSString *)path
                              parameters:(NSDictionary *)parameters
                                progress:(void (^)(NSProgress * _Nonnull))downloadProgress
                                 success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                 failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    if (nil == parameters) {
        parameters = [[NSDictionary alloc] init];
    }
    
    NSURLSessionDataTask *task = [manager GET:baseUrlStr
                                   parameters:parameters
                                     progress:downloadProgress
                                      success:success
                                      failure:failure];
    
    return task;
}


// MARK: -  UPLOAD

- (NSURLSessionDataTask *)uploadWithBaseUrl:(NSString *)baseUrlStr
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                              formDataArray:(NSArray *)formDataArray
                                   progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
                                    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    if (nil == parameters) {
        parameters = [[NSDictionary alloc] init];
    }
    
    NSURLSessionDataTask *task = [manager POST:baseUrlStr
                                    parameters:parameters
                     constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                         
                         [formData appendPartWithFileData:[formDataArray objectAtIndex:0]
                                                     name:[formDataArray objectAtIndex:1]
                                                 fileName:[formDataArray objectAtIndex:2]
                                                 mimeType:[formDataArray objectAtIndex:3]];
                     }
                                      progress:uploadProgress
                                       success:success
                                       failure:failure];
    
    return task;
}


// MARK: -  PUT

- (NSURLSessionDataTask * )putWithBaseUrl:(NSString *)baseUrlStr
                                     path:(NSString *)path
                               parameters:(NSDictionary *)parameters
                                  success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                  failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    if (nil == parameters) {
        parameters = [[NSDictionary alloc] init];
    }
    
    NSURLSessionDataTask *task = [manager PUT:baseUrlStr parameters:parameters success:success failure:failure];
    
    return task;
    
}

// MARK: -  DELETE

- (NSURLSessionDataTask *)deleteWithBaseUrl:(NSString *)baseUrlStr
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                                    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self createSessionManagerWithUrl:baseUrlStr];
    
    if (nil == parameters) {
        parameters = [[NSDictionary alloc] init];
    }
    
    NSURLSessionDataTask *task = [manager DELETE:baseUrlStr parameters:parameters success:success failure:failure];
    
    return task;
    
}


// MARK: -  Setter Getter Methods

- (NSMutableDictionary *)sessionManagerMDic
{
    if (nil == _sessionManagerMDic) {
        _sessionManagerMDic = [[NSMutableDictionary alloc] initWithCapacity:5];
    }
    
    return _sessionManagerMDic;
}


@end

